<template>
    <div>
        <!-- 参数表单 -->
        <div class="params-form">
            <el-form :inline="true" label-width="120px">
                <el-form-item label="流域面积 (F)">
                    <el-input-number v-model="designParams.F" :step="0.1" ></el-input-number>
                </el-form-item>
                <el-form-item label="洪水胖瘦系数 (w)">
                    <el-input-number v-model="w" :min="0.1" :max="0.6" step="0.01"></el-input-number>
                </el-form-item>
                <el-form-item label="综合系数 (K)">
                    <el-input-number v-model="K" :min="0.03" :max="0.04" step="0.001"></el-input-number>
                </el-form-item>
                <el-form-item label="选择频率">
                    <el-select v-model="selectedFrequency" placeholder="请选择频率">
                        <el-option label="全部显示" value="all"></el-option>
                        <el-option v-for="item in flowResultData" :key="item.frequency" :label="`${item.frequency} %`"
                            :value="item.frequency" />
                    </el-select>
                </el-form-item>
            </el-form>
            <div class="button-group">
                <el-button type="primary" @click="recalculate">重新计算</el-button>
                <el-button type="success" @click="exportData">导出</el-button>
            </div>
        </div>
        <!-- 流量过程线 -->
        <div id="chartContainer" style="width: 100%; height: 400px; margin-top: 20px;"></div>
        <!-- 设计洪水成果表 -->
        <el-row style="margin: 20px 0; ">
            <el-col :span="24">
                <h1 style="margin: 20px 0; ">设计洪水成果表</h1>
                <el-table :data="resultsTable" style="width: 100%" border>
                    <el-table-column prop="frequency" label="频率 (%)"></el-table-column>
                    <el-table-column prop="QMax" label="Qm (m³/s)"></el-table-column>
                    <el-table-column prop="tau" label="τ (h)"></el-table-column>
                    <el-table-column prop="psi" label="ψ"></el-table-column>
                    <el-table-column prop="n" label="n"></el-table-column>
                </el-table>
            </el-col>
        </el-row>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, nextTick, watch } from "vue";
import * as echarts from "echarts";
import { ElMessage } from 'element-plus';

// 接收父组件传来的数据
const props = defineProps({
    resultsData: {
        type: Object,
        required: true,
    },
});

// 提取设计参数和初始数据
const designParams = reactive({
    F: parseFloat(props.resultsData.designParams["流域面积F"]),
});
const flowResultData = reactive([...props.resultsData.flowResultData]);

// 可调整参数
const K = ref(0.035); // 可变系数
const w = ref(0.42); // 洪水胖瘦系数

// 当前选择的频率
const selectedFrequency = ref("all"); // 默认选择 "全部显示"

// 表格数据和图表数据
const resultsTable = reactive([]);
let chartInstance = null; // 图表实例

// 保存流量过程线数据
const processData = reactive({});

// YDatas 和 XDatas (模拟数据)
const YDatas = [0, 10, 20, 40, 60, 80, 90, 100, 90, 80, 60, 40, 20, 10, 0];
const WDatas = [0.25, 0.30, 0.36, 0.41, 0.42, 0.48, 0.52];
const XDatas = [
    [0, 0, 0, 0, 0, 0, 0],
    [0.5, 4.5, 5.5, 3.5, 1.5, 4, 4],
    [1, 7.5, 9.5, 6.9, 5, 7, 9],
    [2, 9.5, 12, 9.7, 8, 12.5, 14],
    [2.5, 11, 13, 10.5, 9.5, 16, 18],
    [3.5, 12.2, 14.5, 12.2, 14, 19, 22.5],
    [4.5, 13, 15, 14, 16.5, 22.5, 24.5],
    [6.5, 14.5, 17.5, 21.3, 22, 25.5, 29],
    [9.5, 19, 25.5, 31.3, 29.5, 37, 40],
    [11, 21, 28, 36, 33, 42, 47],
    [16.5, 26, 34, 43.6, 41.5, 56.5, 60.5],
    [23, 37, 44.5, 51.4, 50, 64, 74.5],
    [37, 58, 60, 62.5, 63.5, 81.5, 87],
    [49, 75, 83, 76.1, 86.5, 91, 93],
    [100, 100, 100, 100, 100, 100, 100],
];

// 计算 QMax
const calculateQMax = (F, R, alpha, K) => alpha * K * R * Math.pow(F, 0.75);

// 计算 T
const calculateT = (F, R, w, QMax, dbPer = 1) => (0.278 * F * R) / (w * QMax) * dbPer;

// 计算 TDatas 和 QDatas
const calculateData = (F, R, w, QMax) => {
    const nCount = YDatas.length;
    const TDatas = new Array(nCount).fill(0);
    const QDatas = new Array(nCount).fill(0);

    let WPos = WDatas.findIndex((v) => w <= v);
    if (WPos === -1) WPos = WDatas.length - 1;

    for (let i = 0; i < nCount; i++) {
        const dbPer = XDatas[i][WPos];
        TDatas[i] = calculateT(F, R, w, QMax, dbPer) / 100;
        QDatas[i] = (YDatas[i] * QMax) / 100.0;
    }

    return { TDatas, QDatas };
};

// 针对单一频率重新计算表格和图表
const recalculateSingle = (frequency) => {
    const row = flowResultData.find((item) => item.frequency === frequency);
    if (!row) return;

    const series = [];
    const F = designParams.F;
    const R = parseFloat(row.r);
    const alpha = parseFloat(row.alpha);

    const QMax = calculateQMax(F, R, alpha, K.value);
    const T = calculateT(F, R, w.value, QMax);

    // 更新表格
    resultsTable.length = 0;
    resultsTable.push({
        frequency: row.frequency,
        QMax: QMax.toFixed(2),
        tau: T.toFixed(2),
        psi: row.psi,
        n: 0.75, // 固定值
    });

    // 更新图表
    const { TDatas, QDatas } = calculateData(F, R, w.value, QMax);
    processData[frequency] = { time: TDatas, flow: QDatas };
    
    series.push({
        name: row.frequency,
        type: "line",
        smooth: true,
        data: TDatas.map((t, i) => [t.toFixed(2), QDatas[i]]),
    });

    drawChart(series, true);
};

// 重新计算所有频率的数据
const recalculate = () => {
    resultsTable.length = 0; // 清空表格数据
    const series = [];

    // 清空流量过程线数据
    Object.keys(processData).forEach(key => delete processData[key]);

    flowResultData.forEach((row) => {
        const F = designParams.F;
        const R = parseFloat(row.r);
        const alpha = parseFloat(row.alpha);

        const QMax = calculateQMax(F, R, alpha, K.value);
        const T = calculateT(F, R, w.value, QMax);

        // 更新表格
        resultsTable.push({
            frequency: row.frequency,
            QMax: QMax.toFixed(2),
            tau: T.toFixed(2),
            psi: row.psi,
            n: 0.75, // 固定值
        });

        // 计算图表数据
        const { TDatas, QDatas } = calculateData(F, R, w.value, QMax);
        processData[row.frequency] = { time: TDatas, flow: QDatas };
        console.log(
            {TDatas, QDatas}
        )
        series.push({
            name: row.frequency,
            type: "line",
            smooth: true,
            data: TDatas.map((t, i) => [t.toFixed(2), QDatas[i]]),
        });
    });

    drawChart(series, false);
};

// 绘制图表
const drawChart = (series, showXAxisLabel) => {
    nextTick(() => {
        const chartDom = document.getElementById("chartContainer");
        if (!chartDom) return;

        if (chartInstance) chartInstance.dispose();
        chartInstance = echarts.init(chartDom);

        chartInstance.setOption({
            title: { text: "流量过程线", left: "center", textStyle: { color: '#fff' } },
            tooltip: { trigger: "axis" },
            legend: { bottom: 10, textStyle: { color: '#fff' } },
            xAxis: {
                type: "value",
                name: "时间 (h)",
                axisLabel: { show: showXAxisLabel, color: '#fff' },
                axisLine: { lineStyle: { color: '#fff' } }
            },
            yAxis: {
                type: "value",
                name: "流量 (m³/s)",
                axisLabel: { color: '#fff' },
                axisLine: { lineStyle: { color: '#fff' } }
            },
            series,
            backgroundColor: '#333', // 黑色背景
        });
    });
};

// 导出数据为CSV
const exportData = () => {
    // 导出设计洪水成果表
    let csvContent = "数据类型,数据内容\n";
    csvContent += "设计参数,\n";
    csvContent += `流域面积(F),${designParams.F}\n`;
    csvContent += `洪水胖瘦系数(w),${w.value}\n`;
    csvContent += `综合系数(K),${K.value}\n\n`;
    
    // 导出设计洪水成果表
    csvContent += "设计洪水成果表,\n";
    csvContent += "频率(%),Qm(m³/s),τ(h),ψ,n\n";
    
    resultsTable.forEach(row => {
        csvContent += `${row.frequency},${row.QMax},${row.tau},${row.psi},${row.n}\n`;
    });
    
    // 导出流量过程线数据
    csvContent += "\n流量过程线数据,\n";
    
    // 根据当前选择的频率导出相应的流量过程线数据
    if (selectedFrequency.value === "all") {
        // 如果选择"全部显示"，导出所有频率的数据
        Object.keys(processData).forEach(frequency => {
            const { time, flow } = processData[frequency];
            
            csvContent += `频率(${frequency}%),\n`;
            csvContent += "时间(h),流量(m³/s)\n";
            
            for (let i = 0; i < time.length; i++) {
                csvContent += `${time[i].toFixed(2)},${flow[i].toFixed(2)}\n`;
            }
            
            csvContent += "\n";
        });
    } else {
        // 如果选择特定频率，只导出该频率的数据
        const { time, flow } = processData[selectedFrequency.value];
        
        csvContent += `频率(${selectedFrequency.value}%),\n`;
        csvContent += "时间(h),流量(m³/s)\n";
        
        for (let i = 0; i < time.length; i++) {
            csvContent += `${time[i].toFixed(2)},${flow[i].toFixed(2)}\n`;
        }
    }
    
    // 创建下载链接
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    
    link.setAttribute('href', url);
    link.setAttribute('download', '设计洪水成果.csv');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    ElMessage({
        message: '导出成功',
        type: 'success'
    });
};

// 初始化
onMounted(() => recalculate());

// 监听频率切换
watch(selectedFrequency, (newFrequency) => {
    if (newFrequency === "all") {
        recalculate();
    } else {
        recalculateSingle(newFrequency);
    }
});

// 销毁图表实例
onBeforeUnmount(() => {
    if (chartInstance) chartInstance.dispose();
});
</script>

<style scoped>
.params-form {
    margin-bottom: 20px;
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    color: #fff;
    align-items: flex-start;
}

.button-group {
    display: flex;
    gap: 10px;
}
</style>